package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.InputType;
import android.util.JsonReader;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.utils.Json;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity {

    int start_click_num = 0;

    int end_click_num = 0;

    private boolean isStart = false;

    private MediaRecorder mr = null;

    public String soundPath = null;
    public String soundName = null;

    private Boolean isPlay = false;

    private MediaPlayer player = new MediaPlayer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        toast = initToast();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button1 = findViewById(R.id.start);
        final Button button2 = findViewById(R.id.end);
        final EditText input = findViewById(R.id.editTextTextPersonName);
        final TextView textView1 = findViewById(R.id.text1);
        final Button button3 = findViewById(R.id.button3);
        Button jumphtml = findViewById(R.id.jumphtml);

        // 开始
        button1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                checkPermission();

                input.setInputType(InputType.TYPE_CLASS_TEXT);
                String data = input.getText().toString();
//                if (MainActivity.this.start_click_num++ > 1) {
//                    toast.setText("居然敢点我" + MainActivity.this.start_click_num + "次！！！");
//                } else {
//                    toast.setText("开始！！");
//                }
                toast.setText(data);
                toast.show();
                textView1.setText(data);
            }
        });

        // 结束
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!isStart) {
                    startRecord();
                    button2.setText("停止录制");
                    isStart = true;
                } else {
                    stopRecord();
                    button2.setText("开始录制");
                    isStart = false;
                    upload(textView1);
                }

//                if (MainActivity.this.start_click_num > 1) {
//                    toast.setText("终于结束了。。。感觉身体被掏空");
//                } else if (MainActivity.this.start_click_num < 1) {
//                    toast.setText("还没开始呢baby--|");
//                } else if (MainActivity.this.end_click_num++ > 1) {
//                    toast.setText("別點了");
//                } else {
//                    toast.setText("结束！！");
//                }
//                toast.show();
            }
        });

        // 播放
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (MainActivity.this.soundPath == null) {
                    toast.setText("当前没有录音");
                    toast.show();
                } else {
                    playPrepare();
                    if (!MainActivity.this.isPlay) {
                        // 标记时长
                        textView1.setText(getDuration());
                        MainActivity.this.isPlay = true;
                        button3.setText("停止");
                        startPlay();
                    } else {
                        MainActivity.this.isPlay = false;
                        button3.setText("播放");
                        stopPlay();
                    }
                }
            }
        });

        // 跳转html
        jumphtml.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, HtmlActivity.class);
                startActivity(intent);
            }
        });

    }

    private void upload(final TextView textView) {
        String data = MainActivity.this.soundPath;
        String key = MainActivity.this.soundName;
        final String token = MainActivity.this.getAuthToken();
        UploadManager uploadManager = MainActivity.this.getUploadManager();
        uploadManager.put(data, key, token,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        //res包含hash、key等信息，具体字段取决于上传策略的设置
                        String log = "";
                        if (info.isOK()) {
                            log += "upload success";
                        } else {
                            log += "upload fail";
                            //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                        }

                        log += key + ",\r\n " + info + ",\r\n " + res;
                        try {
                            String key1 = res.getString("key");
                            toast.setText(key1);
                        } catch (JSONException e) {
                            toast.setText("解析失败");
                        }
                        toast.show();
                        textView.setText(log);
                    }
                }, null);
    }

    /**
     * 响应授权
     * 这里不管用户是否拒绝，都进入首页，不再重复申请权限
     */
/*
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_REQUEST:

                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                break;
        }
    }
 */

    // 开始播放
    private void startPlay() {
        MainActivity.this.player.start();
    }

    // 停止播放
    private void stopPlay() {
        MainActivity.this.player.stop();
        MainActivity.this.player.reset();
        MainActivity.this.player.release();
    }

    // 播放prepare
    private void playPrepare() {
        try {
            MainActivity.this.player.setDataSource(MainActivity.this.soundPath);
            MainActivity.this.player.prepare();
        } catch (Exception e) {
            toast.setText(e.getMessage());
            toast.show();
        }
    }

    // 获取时长
    private String getDuration() {
        MediaPlayer player = MainActivity.this.player;
        int duration = player.getDuration();
//        toast.setText(duration);
//        toast.show();
        if (0 != duration) {
            //更新 seekbar 长度
//                seekbar.setMax(duration);
            int s = duration / 1000;
            //设置文件时长，单位 "分:秒" 格式
            String total = s / 60 + ":" + s % 60;
            //记得释放资源
//                player.release();
            return total;
        }
        return "0";
    }

}